<?
/***************************************************************************
*                            Dolphin Smart Community Builder
*                              -------------------
*     begin                : Mon Mar 23 2006
*     copyright            : (C) 2007 BoonEx Group
*     website              : http://www.boonex.com
* This file is part of Dolphin - Smart Community Builder
*
* Dolphin is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the
* License, or  any later version.
*
* Dolphin is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with Dolphin,
* see license.txt file; if not, write to marketing@boonex.com
***************************************************************************/

bx_import('BxDolTwigModule'); 
bx_import('BxDolAdminSettings');

class BxFriendSuggestionModule extends BxDolTwigModule{
 
 
    function BxFriendSuggestionModule(&$aModule) {

        parent::BxDolTwigModule($aModule);        
   
        $GLOBALS['oBxFriendSuggestionModule'] = &$this;
  
	    $this->_oConfig->init($this->_oDb);
	    $this->_oTemplate->init($this->_oDb);  
 
		if( $_REQUEST['show_suggest']=='suggest')
		{ 
			$iProfileID = (int)$_COOKIE['memberID'];

			$this -> hideSuggestion(); 
			echo $this -> getSuggestions($iProfileID);   
			exit;
		} 
	}
 
	/**
	 * 
	 * Admin Settings Methods
	 * 
	 */
	function getSettingsForm($mixedResult) {
	    $iId = (int)$this->_oDb->getOne("SELECT `ID` FROM `sys_options_cats` WHERE `name`='People You May Know'");
	    if(empty($iId))
	       return MsgBox('_Empty');
	       
        $oSettings = new BxDolAdminSettings($iId, BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'admin');
        $sResult = $oSettings->getForm();
        	       
        if($mixedResult !== true && !empty($mixedResult))
            $sResult = $mixedResult . $sResult;

        return $sResult;
	}

	function setSettings($aData) {
	    $iId = (int)$this->_oDb->getOne("SELECT `ID` FROM `sys_options_cats` WHERE `name`='People You May Know'");
	    if(empty($iId))
	       return MsgBox(_t('_Empty'));
	       
	    $oSettings = new BxDolAdminSettings($iId);
	    return $oSettings->saveChanges($_POST);
	} 
 
	function serviceSuggestBlock($iProfileID=0){
	
		$iProfileID = ($iProfileID) ? $iProfileID : (int)$_COOKIE['memberID'];
             
		if(!$iProfileID)
			return;

		$this->_oTemplate->addCss ('friendsuggest.css');

		if(getParam("modzzz_friend_suggest_activated") != "on")
			return;	
	 
		$ret = "<div id='suggest_block' class='pymk_unit'>";
		$ret .= $this->getSuggestions($iProfileID);
		$ret .= '</div>';

		return $ret; 
	}

	function getSuggestions($iProfileID){
 
		global $site;

		$sHideLink = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri();
		$sHideIconUrl = $this->_oTemplate->getIconUrl('suggest_remove.gif');

		$oTemplConfig = new BxTemplConfig( $site );
	 
		$sNoFriendsC = _t("_modzzz_suggest_no_friends");
		$sFriendC = _t('_modzzz_befriend'); 
		$sNoFriendSuggestionsC = _t("_modzzz_no_friend_suggestions");
		$sMessageC = _t("_modzzz_message");
		$sViewFriendsC = _t("_modzzz_view_friends");
	 
		$ret = "<div><b>"._t('_modzzz_friend_suggestion_desc')."</b></div>";

		$ret .= "<div class='clear_both'></div><br>";

		$max_display_num = (int) getParam( "friend_suggest_display_num" );
	  
		$frndQuery = "SELECT `Profiles`.`ID` FROM `sys_friend_list`
			 LEFT JOIN `Profiles` ON (`Profiles`.`ID` = `sys_friend_list`.`Profile` AND `sys_friend_list`.`ID` = '$iProfileID' OR `Profiles`.`ID` = `sys_friend_list`.`ID` AND `sys_friend_list`.`Profile` = '$iProfileID')
			 WHERE (`sys_friend_list`.`Profile` = '$iProfileID' OR `sys_friend_list`.`ID` = '$iProfileID') AND `sys_friend_list`.`Check` = '1' ORDER BY rand()";

		$frndRes = db_res($frndQuery);
		
		$frndCounter = 0;
		 
		$arrX = array();
		$arrY = array();
		$arrHide = array();
		while ( $frndArr = mysql_fetch_assoc( $frndRes ) )
		{
			$frndID = $frndArr['ID']; 
			$arrX[$frndCounter] = $frndID;
			$frndCounter++;
		}
		

		$hideQuery = "SELECT `HideMember` FROM `modzzz_pymk_suggest_hide_list` 
					  WHERE `Member` = '$iProfileID' ";

		$hideRes = db_res($hideQuery);

		$hideCounter = 0;
		while ( $hideArr = mysql_fetch_assoc( $hideRes ) )
		{
			$hideID = $hideArr['HideMember']; 
			$arrHide[$hideCounter] = $hideID;
			$hideCounter++;
		}


		if($frndCounter)
		{
			for($subFrnd=0; $subFrnd<$frndCounter; $subFrnd++)
			{
				$eachFrndID = $arrX[$subFrnd];
				$subFrndQuery = "SELECT `Profiles`.`ID` FROM `sys_friend_list`
						 LEFT JOIN `Profiles` ON (`Profiles`.`ID` = `sys_friend_list`.`Profile` AND `sys_friend_list`.`ID` = '$eachFrndID' OR `Profiles`.`ID` = `sys_friend_list`.`ID` AND `sys_friend_list`.`Profile` = '$eachFrndID')
						 WHERE (`sys_friend_list`.`Profile` = '$eachFrndID' OR `sys_friend_list`.`ID` = '$eachFrndID') AND `sys_friend_list`.`Check` = '1' ORDER BY rand() LIMIT {$max_display_num}";

				$subFrndRes = db_res($subFrndQuery);
	 
				$subFrndCounter = 0;
				$arrY[$arrX[$subFrnd]] = array();
				while ( $subFrndArr = mysql_fetch_assoc( $subFrndRes ) )
				{
					$subFrndID = $subFrndArr['ID'];
					if ((int)$iProfileID == (int)$subFrndID)
						continue;

					if ( in_array($subFrndID, $arrX) )
						continue; 

					if ( in_array($subFrndID, $arrHide) )
						continue; 

					$exists = 0;
					foreach($arrY as $key=>$val)
					{
						if ( in_array($subFrndID, $arrY[$key]) )
						{
							$exists = 1;
							break;
						} 
					}
					if ($exists)
						continue; 
	 
					$arrY[$arrX[$subFrnd]][$subFrndCounter] = $subFrndID;

					$subFrndCounter++;
				} 
				
			}
	 
	 
			$suggestCounter = 0;
			$suggestArr = array();
			for($itemIndex=0; $itemIndex<$max_display_num; $itemIndex++)
			{
				for($frndIndex=0; $frndIndex<$frndCounter; $frndIndex++)
				{
					if($suggestCounter == $max_display_num){ 
						break 2; 
					}
					
					if($itemIndex >= count($arrY[$arrX[$frndIndex]]))
						continue;
	  
					$suggestArr[$suggestCounter][$arrX[$frndIndex]]=$arrY[$arrX[$frndIndex]][$itemIndex];

					$suggestCounter++;
				}

			} 
			 
			for ( $i=0; $i<$suggestCounter; $i++)
			{
				foreach( $suggestArr[$i] as $key=>$val) 
				{ 
					$sMutualFriend = "<a href='" . getProfileLink($key) . "'>" . getNickName($key) . "</a>";

					$sMutualFriendMsg = _t("_modzzz_you_both_know", $sMutualFriend);
	 
					if( ($GLOBALS['site']['ver']=='7.0') && ((int)$GLOBALS['site']['build']<5) ) { 
						$sFriendLinkC = "<a href=\"javascript:void(0);\" title=\"{$sFriendC}\" onclick=\"window.open( 'list_pop.php?action=friend&amp;ID=$val', '', 'width={$oTemplConfig -> popUpWindowWidth},height={$oTemplConfig -> popUpWindowHeight},menubar=no,status=no,resizable=no,scrollbars=yes,toolbar=no,location=no' );\"   class=\"menuLink\">{$sFriendC}</a>";
					}else{ 
						$sFriendLinkC = "<a href=\"javascript:void(0);\" title=\"{$sFriendC}\"  
						onclick=\"$.post('list_pop.php?action=friend', { ID: '{$val}' }, function(sData){ $('#ajax_popup_result_{$val}').html(sData) } );return false;\" 
						class=\"menuLink\">{$sFriendC}</a>";
					}			

					$ret .= "<div class='suggest_outer_block'>" . get_member_icon($val, 'left') . "<div class='suggest_info_block' ><a href='" . getProfileLink($val) . "'>" . getNickName($val) . "</a><br>{$sMutualFriendMsg}<br>{$sFriendLinkC} | <a href='viewFriends.php?iUser=$val'>{$sViewFriendsC}</a> | <a href='mail.php?mode=compose&recipient_id=$val'>{$sMessageC}</a></div><div class='suggest_action_block'><img onclick=\"getHtmlData( 'suggest_block', '{$sHideLink}&hide={$val}&amp;show_suggest=suggest');return false;\" src='{$sHideIconUrl}'></div><div class='clear_both'></div></div>"; 

					$ret .= "<div class='clear_both'></div>";
					$ret .= "<div id='ajax_popup_result_{$val}' style='display:block;'>&nbsp;</div>";

				}
			}

			if($suggestCounter == 0)
			{
				$ret .= MsgBox(_t("_Empty")); 
			} 

		}else{ 
			$ret = "<div class='err'>".MsgBox($sNoFriendsC)."</div>"; 
		}
	  
		return $ret ;
	}
	  
	function hideSuggestion(){
	
		$iProfileID = (int)$_COOKIE['memberID']; 
		$iHide = (int)$_REQUEST['hide'];

		if($iHide)
			db_res("INSERT INTO `modzzz_pymk_suggest_hide_list` SET `Member`=$iProfileID, `HideMember`=$iHide");
	}
 

 
    function actionAdmin ($sUrl = '') {

        if (!$this->isAdmin()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }        

        $this->_oTemplate->pageStart();

        $aMenu = array( 
            'settings' => array(
                'title' => _t('_modzzz_pymk_menu_admin_settings'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'admin/settings',
                '_func' => array ('name' => 'actionAdministrationSettings', 'params' => array()),
            ),
        );

        if (empty($aMenu[$sUrl]))
            $sUrl = 'settings';

        $aMenu[$sUrl]['active'] = 1;
        $sContent = call_user_func_array (array($this, $aMenu[$sUrl]['_func']['name']), $aMenu[$sUrl]['_func']['params']);

        echo $this->_oTemplate->adminBlock ($sContent, _t('_modzzz_pymk_page_title_administration'), $aMenu);
        $this->_oTemplate->addCssAdmin ('admin.css');
        $this->_oTemplate->addCssAdmin ('unit.css');
        $this->_oTemplate->addCssAdmin ('main.css');
        $this->_oTemplate->addCssAdmin ('forms_extra.css'); 
        $this->_oTemplate->addCssAdmin ('forms_adv.css');        
        $this->_oTemplate->pageCodeAdmin (_t('_modzzz_pymk_page_title_administration'));
    }

    function actionAdministrationSettings () {
        return parent::_actionAdministrationSettings ('FriendSuggestion');
    }




}